import { useState, useCallback } from 'react';

const useMultiPageRowSelection = (dataList, rowKeyName) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const reset = useCallback(() => setSelectedRowKeys([]), []);

  const onSelectChange = useCallback((selectedKeys) => {
    // 获取当前页所有的 key
    const allKeysInCurrentPage = dataList.map(item => item[rowKeyName]);
    // 获取非当前页选中的 key
    const selectedKeysNotInCurrentPage = selectedRowKeys.filter(key => !allKeysInCurrentPage.includes(key));
    // 获取当前页选中的的 key
    const selectedKeysInCurrentPage = selectedKeys.filter(key => allKeysInCurrentPage.includes(key));
    // 合并生成新的 selectedRowKeys
    setSelectedRowKeys([...selectedKeysNotInCurrentPage, ...selectedKeysInCurrentPage]);
  }, [dataList, rowKeyName, selectedRowKeys]);

  return [selectedRowKeys, onSelectChange, reset];
};

export default useMultiPageRowSelection;
